﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using mvcForum.Core;

using mvcForum.Web.Controllers;
using mvcForum.Core.Specifications;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class GroupMemberController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult Create(Int32 userId, Int32 groupId, String mode) {
			// TODO: Access!!
			ForumUser user = this.GetRepository<ForumUser>().Read(userId);
			Group group = this.GetRepository<Group>().Read(groupId);

			GroupMember gm = new GroupMember(group, user);
			this.GetRepository<GroupMember>().Create(gm);

			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult Delete(Int32 id, String mode) {
			IRepository<GroupMember> gmRepo = this.GetRepository<GroupMember>();
			// TODO: Access!!
			GroupMember gm = gmRepo.Read(id);

			gmRepo.Delete(gm);

			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}

		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult ListGroups(Int32 id, String mode) {
			// TODO: Access!!!!
			ForumUser user = this.GetRepository<ForumUser>().Read(id);

			IEnumerable<GroupMember> groups = this.GetRepository<GroupMember>().ReadMany(new GroupMemberSpecifications.SpecificUser(user));
			return this.CustomJson(new { Groups = groups.Select(m => new { Id = m.Id, GroupId = m.Group.Id, Name = m.Group.Name }) });
		}

		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult ListMembers(Int32 id, String mode) {
			// TODO: Access!!!!
			Group group = this.GetRepository<Group>().Read(id);

			IEnumerable<GroupMember> groups = this.GetRepository<GroupMember>().ReadMany(new GroupMemberSpecifications.SpecificGroup(group));
			return this.CustomJson(new { Groups = groups.Select(m => new { Id = m.Id, UserId = m.ForumUser.Id, Name = m.ForumUser.Name }) });
		}
	}
}